﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using Wys.EnlishVoice;
namespace Wys.DataForm.CSharp
{
    public partial class Config : Wys.Control.Vb.AutoAdjustFrom
    {   
        public int iItype = 0;     

        #region 构造函数
        public Config()
        {
            InitializeComponent();
        }

        #endregion

        #region  窗体初始化事件
        //2010-03-12 修正皮肤字体的刷新的问题
        private string Back_fontName = ""; 
        //2010-03-12 修正皮肤字体的刷新的问题
        private void Config_Load(object sender, EventArgs e)
        {

            if (GetAppSettingConfig("CtrlKey") == "1")
            {
                this.chkCtrl.Checked = true;
            }
            else
            {
                this.chkCtrl.Checked = false;
            }
            if (GetAppSettingConfig("ShiftKey") == "1")
            {
                this.chkShift.Checked = true;
            }
            else
            {
                this.chkShift.Checked = false;
            }
            if (GetAppSettingConfig("AtlKey") == "1")
            {
                this.chkAlt.Checked = true;
            }
            else
            {
                this.chkAlt.Checked = false;
            }
            cboKeys.Text = GetAppSettingConfig("ShortKey");
            //A-2009-09-30
            if (GetAppSettingConfig("AutoRun") == "1")
            {
                chkStart.Checked = true;
            }
            else
            {
                chkStart.Checked = false;
            }

            cbo类型.SelectedIndex = Int16.Parse(GetAppSettingConfig("ApplicationType"));

            try
            {
                this.numWidth.Value = decimal.Parse(GetAppSettingConfig("FormWidth"));
                this.numHeight.Value = decimal.Parse(GetAppSettingConfig("FormHeight"));
            }
            catch (Exception me)
            {
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
            }
            try
            {
                try
                {
                    int iVoiceJapan = Convert.ToInt32(this.GetAppSettingConfig("voiceJapan"));
                    if (cboJapan.Items.Count > iVoiceJapan)
                    {
                        cboJapan.SelectedIndex = iVoiceJapan;
                    }
                    
                }
                catch (Exception me)
                {
                    UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
                }            
            }
            catch (Exception me)
            {
                //SaveException(me); //D-2009-09-12
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
            }          

            //A-2009-09-05   

            //A-2009-09-07
            int iVolume = Convert.ToInt32(this.GetAppSettingConfig("volume"));
            int iVoiceRate = Convert.ToInt32(this.GetAppSettingConfig("voiceRate"));

            if (iVolume > tbVolume.Maximum)
                iVolume = tbVolume.Maximum;
            if (iVolume < tbVolume.Minimum)
                iVolume = tbVolume.Minimum;
            lblVolume.Text = iVolume.ToString();
            tbVolume.Value = iVolume;

            if (iVoiceRate > this.tbVoiceRate.Maximum)
                iVoiceRate = tbVoiceRate.Maximum;
            if (iVoiceRate < tbVoiceRate.Minimum)
                iVoiceRate = tbVoiceRate.Minimum;
            lblVoiceRate.Text = iVoiceRate.ToString();
            tbVoiceRate.Value = iVoiceRate;
            //A-2009-09-07

            //A-2009-09-12
            this.txtBackupDatabaseFolder.Text = this.GetAppSettingConfig("DataBaseBackUp");
            //A-2009-09-12
          
            //A-2009-10-11

            //A-2009-09-23
            try
            {              
                SetFontChild();
                Font font = null;

                if (this.GetAppSettingConfig("FormFontName").Trim() == string.Empty)
                {
                    this.cboFont.Text = this.Font.Name;
                    font = new System.Drawing.Font(this.Font.Name, this.txtFontChinese.Font.Size , System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
                }
                else
                {
                    this.cboFont.Text = this.GetAppSettingConfig("FormFontName");
                    font = new System.Drawing.Font(this.cboFont.Text, this.txtFontChinese.Font.Size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);

                }              

                this.txtFontChinese.Font = font;
                this.txtFontEnglish.Font = font;
                this.txtFontJapan.Font = font;
                //2010-03-12 修正皮肤字体的刷新的问题
                this.Back_fontName = this.cboFont.Text;                
                //2010-03-12 修正皮肤字体的刷新的问题
                txtPath3.Text = this.GetAppSettingConfig("synchronizatePath").Trim();
            }
            catch (Exception e1)
            {
                //SaveException(e1);
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, e1, MethodBase.GetCurrentMethod().GetType());
            }           
           
            try
            {
                InitSpeech();
                txtTtsJapanese.CheckedChanged += new System.EventHandler(this.speech_CheckedChanged);
                //日语TTS
                if (this.GetAppSettingConfig("voiceJapaneseTypeTTS").Trim() == "1")
                {
                    txtTtsJapanese.Checked = true;
                    SetSpeech(txtTtsJapanese, true);                
                }
                else
                {
                    txtTtsJapanese.Checked = false;
                    SetSpeech(txtTtsJapanese, false); 
                }
                //日语真人
                if (this.GetAppSettingConfig("voiceJapaneseType").Trim() == "1")
                {
                }
                else
                {
                      
                }
                //英语TTS
                if (this.GetAppSettingConfig("voiceEnglishTypeTTS").Trim() == "1")
                {
                                     
                }
                else
                {
                   
                }

                //英语真人相对路径
                if (this.GetAppSettingConfig("voiceEnglishType").Trim() == "1")
                {
                                      
                }
                else
                {
                  
                }

                if (this.GetAppSettingConfig("voicSpeechEnglish").Trim() != "")
                {
                    
                }
                //英语真人绝对路径
                if (this.GetAppSettingConfig("voiceEnglishTypeAbsolute").Trim() == "1")
                {
                           
                }
                else
                {
                   
                }
                txtSpeachEnglishObsulte.Text = this.GetAppSettingConfig("EngLishVoiceLibId").Trim();
                //汉语真人
                if (this.GetAppSettingConfig("voiceChineseType").Trim() == "1")
                {
                   
                }
                else
                {
                   
                }
               
            }
            catch ( Exception me)
            {
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
            }
            //A-2009-12-23

        }
        //增加真人发声功能 A-2009-12-23
        private void speech_CheckedChanged(object sender, EventArgs e)
        {
            System.Windows.Forms.CheckBox  mychk = sender as System.Windows.Forms.CheckBox ;
            if (mychk != null)
            {
                SetSpeech(mychk, mychk.Checked);
            }
        }

        private void InitSpeech()
        {
            String strTemp = this.GetCurrentDirectory();         
        }
        //建立单词索引文件
        private void SetWordIndex(object sender, EventArgs e)
        {
            string title = this.Text;
            System.Windows.Forms.Button mb = sender as System.Windows.Forms.Button;
            if (mb != null)
            {
                if (mb.Name == "btnSpeechEnglish")
                {
                    SetWordIndexDo(0,0);
                    
                }
                else if (mb.Name == "btnSpeechJapanse")
                {
                    SetWordIndexDo(1, 0);
                }
                else if (mb.Name == "btnSpeechChinse")
                {
                    SetWordIndexDo(2, 0);
                }
            }
            this.Text = title;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">0 英语 1 日语 2 汉语</param>
        /// <param name="pathType">0 相对路径 1 为绝对路径</param>
        private void SetWordIndexDo(int type,int pathType)
        {
            ////英语单词
            //if (type == 0)
            //{
            //    this.groupBox1.Enabled = false;
            //    this.tabControlEnglish.Enabled = false;             
            //    this.groupBox4.Enabled = false;             
                
            //    if(pathType==1)
            //    {
            //        if (txtSpeachEnglishObsulte.Text.TrimEnd() == "")
            //        {
            //            ShowMessageBox("请选择文件夹");
            //            return;
            //        }
            //    }
            //    try
            //    {
            //        Control.CheckForIllegalCrossThreadCalls = false;

            //        //String strPath = System.IO.Path.Combine(this.GetCurrentDirectory(), @"speech\English");
            //        //相对路径的时候 文件的位置
            //        //if (pathType == 0)
            //        //{
            //        //    strPath = System.IO.Path.Combine(strPath, myEdit1.Text.Trim());
            //        //}
            //        //strPath = System.IO.Path.Combine(strPath, "Voice.config");

            //        ////存在的话删除
            //        //if (File.Exists(strPath))
            //        //{
            //        //    System.IO.File.Delete(strPath);
            //        //}                  

            //        String strTargetPath = "";

            //        if (pathType == 0)
            //        {
            //            strTargetPath = System.IO.Path.Combine(this.GetCurrentDirectory(), @"speech\English");                                   }
            //        else if (pathType == 1) //绝对路径的情况 路径就在
            //        {
            //            strTargetPath = txtSpeachEnglishObsulte.Text.TrimEnd();
            //        }                  

            //        //开始枚举文件夹的文件
            //        if (System.IO.Directory.Exists(strTargetPath))
            //        {
            //            //CConfigWriter cw = new CConfigWriter();
            //            //cw.CreateXW(strPath);
            //            DateTime dt = DateTime.Now;
            //            EnumFile(strTargetPath, "", 0);
            //            DateTime dt1 = DateTime.Now;
            //            TimeSpan ts = dt1.Subtract(dt);
            //            ShowMessageBox("共消耗了" + ts.TotalMinutes.ToString() + "分钟\r\n大约 " + ts.TotalSeconds.ToString() + "秒\r\n共" + count.ToString() + "条记录");
            //            //cw.CloseXW();
            //        }
            //        else //不存在文件夹的话报错
            //        {
            //            ShowMessageBox("查找不到此文件夹:"+strTargetPath);
            //        }
                   
            //        this.Text = "永胜数据库系统配置 成功"; 
            //        this.groupBox1.Enabled = true;
            //        this.tabControlEnglish.Enabled = true;
            //        this.groupBox4.Enabled = true;                   
            //    }
            //    catch (Exception me)
            //    {
            //        this.Text = "永胜数据库系统配置 失败";                    
            //        this.groupBox1.Enabled = true;
            //        this.tabControlEnglish.Enabled = true;
            //        this.groupBox4.Enabled = true;                   
            //        UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
            //    }
            //}//日语单词
            //else if (type == 1)
            //{

            //}//汉语单词
            //else if (type == 2)
            //{

            //}
       }

        int count = 0;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strParentPath"></param>
        /// <param name="strParnetName"></param>     
        /// <param name="type">0为相对路径 1 为绝对路径</param>
        public void EnumFile(String strParentPath, String strParnetName,int type)
        {      
            count = 0;
            ct.ExecuteSql("DELETE FROM XSCWORDVoice");
            ct.CloseAllDb();

            using (System.Data.SQLite.SQLiteConnection cn = new System.Data.SQLite.SQLiteConnection())
            {
                cn.ConnectionString = "Data Source=" + System.IO.Path.Combine(this.GetCurrentDirectory(), @"SQLITEDATA\XSC.db");
                cn.Open();
                System.Data.SQLite.SQLiteTransaction st = cn.BeginTransaction();

                System.Data.SQLite.SQLiteCommand scmd = new System.Data.SQLite.SQLiteCommand();
                scmd.CommandText = "Insert into XSCWORDVoice(WORD,WORDPATH) VALUES(@WORD,@WORDPATH)";
                System.Data.SQLite.SQLiteParameter sp = new System.Data.SQLite.SQLiteParameter("@WORD");
                scmd.Parameters.Add(sp);
                sp = new System.Data.SQLite.SQLiteParameter("@WORDPATH");
                scmd.Parameters.Add(sp);

                scmd.Connection = cn;
                scmd.Transaction = st;

                String strCurr = System.IO.Path.Combine(GetCurrentDirectory(), @"speech\English");
                try
                {
                    string[] finResult = Directory.GetFiles(strParentPath, "*.*", SearchOption.AllDirectories);
                    if (type == 0)
                    {
                        for (int i = 0; i < finResult.Length; i++)
                        {
                            scmd.Parameters[0].Value = System.IO.Path.GetFileNameWithoutExtension(finResult[i]);
                            scmd.Parameters[1].Value = finResult[i];
                            scmd.ExecuteNonQuery();
                            if ((count++) % 500 == 0)
                            {
                                this.Text = "已经索引了 " + count.ToString() + "条记录";
                                System.Windows.Forms.Application.DoEvents();
                            }
                        }
                    }
                    st.Commit();
                }
                catch (Exception me)
                {
                    st.Rollback();
                    UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
                }
            };                   
        }        
        //增加真人发声功能 A-2009-12-23
        #endregion

        #region 关闭窗体按钮
        private void btnUserClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion     

        #region  配置启动用户
        private void btnUserOk_Click(object sender, EventArgs e)
        {
            //if (!String.IsNullOrEmpty(this.cboFiles.Text))
            //{
                OpenConfig();
               
                SaveConfig();
                ShowMessageBox("更新成功");
                this.Close();
            //}
        }

        #endregion

        #region 设置皮肤文件夹
        /// <summary>
        /// 设置皮肤文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSkipOk_Click(object sender, EventArgs e)
        {
            try
            {
                OpenConfig();               
                this.SetappSettings("FormFontName", this.cboFont.Text);
                this.SetappSettings("FormWidth", this.numWidth.Value.ToString());
                this.SetappSettings("FormHeight", this.numHeight.Value.ToString());  
               
                if (chkCtrl.Checked)
                {
                    SetappSettings("CtrlKey", "1");
                }
                else
                {
                    SetappSettings("CtrlKey", "0");
                }
                if (chkAlt.Checked)
                {
                    SetappSettings("AtlKey", "1");
                }
                else
                {
                    SetappSettings("AtlKey", "0");
                }
                if (chkShift.Checked)
                {
                    SetappSettings("ShiftKey", "1");
                }
                else
                {
                    SetappSettings("ShiftKey", "0");
                }
                SetappSettings("ShortKey", this.cboKeys.Text);
                SetappSettings("ApplicationType", this.cbo类型.SelectedIndex.ToString());    

                //修正字体没有改变的时候 还刷新皮肤的问题 2010-03-13
                if ((Back_fontName != this.cboFont.Text))
                {
                     //设置父窗体的字体
                     Wys.Control.Vb.AutoAdjustFrom frm = this.Owner as Wys.Control.Vb.AutoAdjustFrom;
                     if (frm != null)
                     {
                         frm.SetFont();
                     }
                    this.SetFont();
                }
                //修正字体没有改变的时候 还刷新皮肤的问题 2010-03-13              
                String strExecuteName = System.IO.Path.Combine(GetCurrentDirectory(), "\\Fetion.exe");
                if (chkStart.Checked)
                {
                    RunWhenStart(true, "wysStartUp", strExecuteName);
                    this.SetappSettings("AutoRun", "1");
                }
                else
                {
                    RunWhenStart(false, "wysStartUp", strExecuteName);
                    this.SetappSettings("AutoRun", "0");
                }              
               
                this.SetappSettings("DataBaseBackUp", txtBackupDatabaseFolder.Text);
                this.SetappSettings("EngLishVoiceLibId", txtSpeachEnglishObsulte.Text);
                //日语设置          
                this.SetappSettings("voiceJapaneseType", "0");
                if (txtTtsJapanese.Checked)
                {
                    if (cboJapan.Text.TrimEnd() == "")
                    {
                        this.SetappSettings("voiceJapaneseTypeTTS", "0");
                    }
                    else
                    {
                        this.SetappSettings("voiceJapaneseTypeTTS", "1");
                        this.SetappSettings("voiceJapan", cboJapan.SelectedIndex.ToString());
                    }
                }
                else
                {
                    this.SetappSettings("voiceJapaneseTypeTTS", "0");
                }

                //速率设置
                this.SetappSettings("voiceRate", this.tbVoiceRate.Value.ToString());
                //音量设置
                this.SetappSettings("volume", this.tbVolume.Value.ToString());
                this.SetappSettings("synchronizatePath", this.txtPath3.Text); 
                SaveConfig();
                ShowMessageBox("更新成功"); 
                this.Close();
            }
            catch (Exception me)
            {
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());
            }            
        }
        #endregion

        #region 确定开始是否自动启动
        /// <summary>
        /// 确定开始是否自动启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            //String strExecuteName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            ////A-2009-10-01
            //if(!(UTIL.CUtil.FrameworkVersion()))
            //{
               String strExecuteName  = System.IO.Path.Combine(GetCurrentDirectory(),"\\Fetion.exe");
            //}           
            //A-2009-10-01
            OpenConfig();//A-2009-09-30
            if (chkStart.Checked)
            {
                //RunWhenStart(true, "wysStartUp", Application.StartupPath + "\\FetionFx.exe");
                RunWhenStart(true, "wysStartUp", strExecuteName);
                this.SetappSettings("AutoRun", "1");//A-2009-09-30
                ShowMessageBox("更新成功");
            }
            else
            {
                //RunWhenStart(false, "wysStartUp", Application.StartupPath + "\\FetionFx.exe");
                RunWhenStart(false, "wysStartUp", strExecuteName);
                this.SetappSettings("AutoRun", "0");
                ShowMessageBox("更新成功");//A-2009-09-30
            }
            SaveConfig();//A-2009-09-30
        }

        #endregion

        #region 设置系统热键
        private void myButton1_Click(object sender, EventArgs e)
        {
            OpenConfig();
           
            SaveConfig();
            ShowMessageBox("保存成功,下次启动生效");
        }

        #endregion      

        #region 热键恢复
        private void myButton2_Click(object sender, EventArgs e)
        {
            OpenConfig();
            chkCtrl.Checked = true;
            SetappSettings("CtrlKey", "1");
            chkAlt.Checked = true;
            SetappSettings("AtlKey", "1");
            SetappSettings("ShiftKey", "1");
            this.chkShift.Checked = true;
            this.cboKeys.Text = "W";
            SetappSettings("ShortKey", "W");
            SaveConfig();
            ShowMessageBox("恢复成功");
        }
        #endregion              
       
        #region 朗读声音配置 A-2009-09-05
        private void btnVocieOk_Click(object sender, EventArgs e)
        {
            OpenConfig();
            //A-2009-12-13
                    
            SaveConfig();
            ShowMessageBox("更新成功");
            this.Close();
        }
        #endregion                   

        #region 跟踪条事件 A-2009-09-07
        private void tbVolume_Scroll(object sender, EventArgs e)
        {
            lblVolume.Text = tbVolume.Value.ToString();
        }
        #endregion

        #region 跟踪条事件 A-2009-09-07
        private void tbVoiceRate_Scroll(object sender, EventArgs e)
        {
            lblVoiceRate.Text = this.tbVoiceRate.Value.ToString();
        }
        #endregion    

        #region 试听按钮事件 A-2009-09-07
        private void btnPreListenJapanese_Click(object sender, EventArgs e)
        {
            btnPreListenJapanese.Enabled = false;
            UTIL.CTextVoice.SpeckPreListen(2, cboJapan.SelectedIndex, tbVolume.Value, tbVoiceRate.Value);
            btnPreListenJapanese.Enabled = true;
        }             
        #endregion        

        #region 备份文件夹模块 A-2009-09-12 备份文件夹模块 
        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.SelectedPath = this.txtBackupDatabaseFolder.Text;
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txtBackupDatabaseFolder.Text = this.folderBrowserDialog1.SelectedPath;
            }
        }            

        private void btnBackupSave_Click(object sender, EventArgs e)
        {
            OpenConfig();
            this.SetappSettings("DataBaseBackUp", txtBackupDatabaseFolder.Text);
            SaveConfig();
            ShowMessageBox("更新成功");
            this.Close();
        }

        private void btnBackupClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region 设置字体 A-2009-09-23
        public void SetFontChild()
        {
            System.Drawing.Text.InstalledFontCollection ifc = new System.Drawing.Text.InstalledFontCollection();
            this.cboFont.DataSource = ifc.Families;
            this.cboFont.DisplayMember = "Name";       
        }     
        private void cboFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {              
                Font font = new System.Drawing.Font(this.cboFont.Text, this.txtFontChinese.Font.Size , System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
                this.txtFontChinese.Font = font;
                this.txtFontEnglish.Font = font;
                this.txtFontJapan.Font = font;
            }
            catch (Exception me)
            {
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType()); //A-2009-10-11 
            }
            
        }
        #endregion       

        #region 新增语音控制功能 真人发音设置 A-2009-12-23
        private void SetSpeech( System.Windows.Forms.CheckBox  mcx, bool bState)
            {
                if (mcx.Name == "txtTtsJapanese")
                {
                    cboJapan.Enabled = bState;
                    btnPreListenJapanese.Enabled = bState;
                }
                else if (mcx.Name == "txtSpeachEnglish")
                {

                    
                }              
                else if (mcx.Name == "radEnglishObsulte")
                {
                    txtSpeachEnglishObsulte.Enabled = bState;
                    myButton1.Enabled = bState;
                    //myButton2.Enabled = bState;
                }

                if (this.txtTtsJapanese.Checked )
                {
                    this.groupBox4.Enabled = true;
                }
                else
                {
                    this.groupBox4.Enabled = false;
                }
            }
        #endregion      

        private void myButton1_Click_1(object sender, EventArgs e)
        {
            if(txtSpeachEnglishObsulte.Text.Trim()=="")
            {
                txtSpeachEnglishObsulte.Text="000006";
            }          
            using (ProjectForm profrm = new ProjectForm(this.得到英语发音字符串(),txtSpeachEnglishObsulte.Text))
            {
                if(profrm.ShowDialog()==DialogResult.OK)
                {
                    txtSpeachEnglishObsulte.Text=profrm.选择编号;
                }
            }            
       }
        private void myButton2_Click_1(object sender, EventArgs e)
        {
            SetWordIndexDo(0, 1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String strSql = "Update XSCFormData set FontName=''";
            ct.ExecuteSql(strSql);
            ShowMessageBox("初始化字体成功");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String strSql = "Update XSCFormData set GridRowCount=0";
            ct.ExecuteSql(strSql);
            ShowMessageBox("初始化行数成功");
        }

        private void tabPage3_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.SelectedPath = this.txtPath3.Text;
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txtPath3.Text = this.folderBrowserDialog1.SelectedPath;
            }
        }                   
    }
}
